import { View, ScrollView, TextInput } from 'react-native';
import React, { useState, useEffect } from 'react';
import { Toast } from '@ant-design/react-native';
import PropTypes from 'prop-types';
import AddButton from '../AddButton';
import List from './components/List';
import { createNoteTable, selectNotes, searchNote } from '../../comconfig/sqlfun';

const NoteBookView = ({ navigation, route }) => {
    const { title, id } = route.params;
    const [noteList, setNoteList] = useState([]);
    const [value, onChangeText] = useState('');
    navigation.setOptions({
        title,
        headerTitleStyle: {
            color: '#0079FF',
        },
    });

    const getNotes = async () => {
        try {
            const list = await selectNotes(parseInt(id, 10));
            const arr = [];
            for (let i = 0; i < list.length; i += 1) {
                arr.push(JSON.parse(list[i]));
            }
            setNoteList(arr);
        } catch (error) {
            Toast.info('获取数据失败', 1, undefined, false);
        }
    };
    const search = async () => {
        try {
            const list = await searchNote(value.trim(), parseInt(id, 10));
            const arr = [];
            for (let i = 0; i < list.length; i += 1) {
                arr.push(JSON.parse(list[i]));
            }
            setNoteList(arr);
        } catch (error) {
            Toast.info('获取数据失败', 1, undefined, false);
        }
    };
    useEffect(() => {
        createNoteTable(parseInt(id, 10));
    }, []);
    useEffect(() => {
        if (value.trim() === '') {
            getNotes();
        } else {
            search();
        }
    }, [value]);
    return (
        <View>
            <TextInput
                style={{
                    height: 45,
                    borderWidth: 2,
                    color: '#0079FF',
                    fontSize: 18,
                    borderRadius: 5,
                    borderColor: '#9CDCFE',
                }}
                onChangeText={text => onChangeText(text)}
                value={value}
                placeholder="搜索"
            />
            <ScrollView>
                <List navigation={navigation} noteList={noteList} getList={getNotes} bookid={id} />
            </ScrollView>
            <AddButton
                navigation={navigation}
                getList={getNotes}
                action="添加笔记"
                id={parseInt(id, 10)}
            />
        </View>
    );
};
NoteBookView.defaultProps = {
    route: {},
};
NoteBookView.propTypes = {
    route: PropTypes.objectOf(PropTypes.any),

};
export default NoteBookView;
